<script lang="ts" setup>
  import { uploadImage } from '@/api/common';
  import { ref } from 'vue';
  import { useFileDialog } from '@vueuse/core';

  defineProps<{
    modelValue?: string;
    coverUrl?: string;
  }>();

  const emit = defineEmits(['update:modelValue']);
  const { open, reset, onChange } = useFileDialog({
    accept: '.mp4',
    multiple: false,
  });

  const uploading = ref(false);

  onChange(async (files) => {
    if (files && files.length === 1) {
      const fd = new FormData();
      fd.append('upload', files[0]);
      uploading.value = true;
      const res = await uploadImage(fd, new AbortController());
      uploading.value = false;
      emit('update:modelValue', res.data.data);
      reset();
    }
  });

  const beginUpload = () => {
    open();
  };
</script>

<template>
  <a-spin :loading="uploading">
    <div class="video-upload">
      <div v-if="modelValue">
        <video :src="modelValue" controls style="width: 300px" />
        <div>
          <a-link @click="beginUpload">
            <icon-upload />
            更换视频
          </a-link>
        </div>
      </div>
      <a-link v-else @click="beginUpload">
        <icon-upload />
        上传视频
      </a-link>
    </div>
  </a-spin>
</template>
